package com.ruoyi.xp.seller.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.ruoyi.xp.common.constant.XpConstants;
import com.ruoyi.xp.seller.dto.item.XpSellerResDto;
import com.ruoyi.xp.seller.mapstruct.XpSellerItemMap;
import com.ruoyi.xp.seller.shop.WomenShoesShop;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.xp.seller.mapper.XpSellerItemInfoMapper;
import com.ruoyi.xp.seller.domain.XpSellerItemInfo;
import com.ruoyi.xp.seller.service.IXpSellerItemInfoService;
import com.ruoyi.xp.seller.dto.item.XpSellerItemResDto;
import com.ruoyi.common.core.text.Convert;

import javax.annotation.Resource;

/**
 * 虾皮卖家商品轨迹信息Service业务层处理
 * 
 * @author chdx
 * @date 2022-11-26
 */
@Service
public class XpSellerItemInfoServiceImpl implements IXpSellerItemInfoService
{

    private static final Logger log = LoggerFactory.getLogger(XpSellerItemInfoServiceImpl.class);

    @Autowired
    private XpSellerItemInfoMapper xpSellerItemInfoMapper;

    @Resource
    private XpSellerItemMap xpSellerItemMap;

    /**
     * 查询虾皮卖家商品轨迹信息
     * 
     * @param infoId 虾皮卖家商品轨迹信息主键
     * @return 虾皮卖家商品轨迹信息
     */
    @Override
    public XpSellerItemInfo selectXpSellerItemInfoByInfoId(Long infoId)
    {
        return xpSellerItemInfoMapper.selectXpSellerItemInfoByInfoId(infoId);
    }

    /**
     * 查询虾皮卖家商品轨迹信息列表
     * 
     * @param xpSellerItemInfo 虾皮卖家商品轨迹信息
     * @return 虾皮卖家商品轨迹信息
     */
    @Override
    public List<XpSellerItemInfo> selectXpSellerItemInfoList(XpSellerItemInfo xpSellerItemInfo)
    {
        return xpSellerItemInfoMapper.selectXpSellerItemInfoList(xpSellerItemInfo);
    }

    /**
     * 新增虾皮卖家商品轨迹信息
     * 
     * @param xpSellerItemInfo 虾皮卖家商品轨迹信息
     * @return 结果
     */
    @Override
    public int insertXpSellerItemInfo(XpSellerItemInfo xpSellerItemInfo)
    {
        return xpSellerItemInfoMapper.insertXpSellerItemInfo(xpSellerItemInfo);
    }

    /**
     * 修改虾皮卖家商品轨迹信息
     * 
     * @param xpSellerItemInfo 虾皮卖家商品轨迹信息
     * @return 结果
     */
    @Override
    public int updateXpSellerItemInfo(XpSellerItemInfo xpSellerItemInfo)
    {
        return xpSellerItemInfoMapper.updateXpSellerItemInfo(xpSellerItemInfo);
    }

    /**
     * 批量删除虾皮卖家商品轨迹信息
     * 
     * @param infoIds 需要删除的虾皮卖家商品轨迹信息主键
     * @return 结果
     */
    @Override
    public int deleteXpSellerItemInfoByInfoIds(String infoIds)
    {
        return xpSellerItemInfoMapper.deleteXpSellerItemInfoByInfoIds(Convert.toStrArray(infoIds));
    }

    /**
     * 删除虾皮卖家商品轨迹信息信息
     * 
     * @param infoId 虾皮卖家商品轨迹信息主键
     * @return 结果
     */
    @Override
    public int deleteXpSellerItemInfoByInfoId(Long infoId)
    {
        return xpSellerItemInfoMapper.deleteXpSellerItemInfoByInfoId(infoId);
    }

    @Override
    public void getSellerRecommend() throws IOException, InterruptedException {

        Long batchId = System.currentTimeMillis();
        log.info("开始获取买家商品信息:{}", batchId);
        BigDecimal baseNum = new BigDecimal(100000);

        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Date now = null;
        Date beginTime = null;
        Date endTime = null;
        try {
            now = df.parse(df.format(new Date()));
            beginTime = df.parse("00:00");
            endTime = df.parse("23:59");
        } catch (Exception e) {
            e.printStackTrace();
        }

        boolean isGetTime = belongCalendar(now, beginTime, endTime);


        for (WomenShoesShop womenShoesShop : WomenShoesShop.values()) {

            log.info("ShopName : {}", womenShoesShop.getShopName());

            if (!womenShoesShop.isGetEveryHour() && !isGetTime) {
                log.info("ShopName is not in get time {} ", now);
                continue;
            }

            Integer page = 0;
            Integer pageSize = 30;
            boolean isBreak = true;
            while (isBreak) {
                XpSellerResDto xpSellerResDto = getItemInfo(womenShoesShop.getCountry(), womenShoesShop.getShopId(), pageSize, page * pageSize);
                if (xpSellerResDto != null && xpSellerResDto.getData() != null && xpSellerResDto.getData().getSections() != null &&
                        xpSellerResDto.getData().getSections().get(0) != null && xpSellerResDto.getData().getSections().get(0).getData() != null &&
                        xpSellerResDto.getData().getSections().get(0).getData().getItem() != null) {
                    //XpSellerItemDataResDto xpSellerItemDataResDto = xpSellerResDto.getData().getSections().get(0).getData();
                    for (XpSellerItemResDto xpSellerItemResDto : xpSellerResDto.getData().getSections().get(0).getData().getItem()) {
                        XpSellerItemInfo entity = xpSellerItemMap.sellerItemDtoToEntity(xpSellerItemResDto);
                        entity.setBatchId(batchId);
                        entity.setShopName(womenShoesShop.getShopName());
                        entity.setShopUrl(womenShoesShop.getShopURL());
                        Timestamp ts = new Timestamp(new Long(entity.getCtime()) * 1000);
                        entity.setCtime(ts.toString().substring(0, 10));
                        entity.setPrice(entity.getPrice().divide(baseNum));
                        entity.setPriceCny(entity.getPrice().multiply(new BigDecimal(getRate(womenShoesShop.getCountry()))));
                        entity.setPriceMin(entity.getPriceMin().divide(baseNum));
                        entity.setPriceMax(entity.getPriceMax().divide(baseNum));
                        entity.setPriceMinBeforeDiscount(entity.getPriceMinBeforeDiscount().divide(baseNum));
                        entity.setPriceMaxBeforeDiscount(entity.getPriceMaxBeforeDiscount().divide(baseNum));
                        entity.setPriceBeforeDiscount(entity.getPriceBeforeDiscount().divide(baseNum));
                        entity.setCountry(womenShoesShop.getCountry());
                        entity.setCreateDate(new Date());
                        xpSellerItemInfoMapper.insertXpSellerItemInfo(entity);
                    }
                    int total = xpSellerResDto.getData().getSections().get(0).getTotal();
                    if (total < (page + 1) * pageSize) {
                        isBreak = false;
                    }
                    page++;
                } else {
                    isBreak = false;
                }
                //Thread.sleep(1000);
            }
        }
        log.info("结束获取买家商品信息:{}", batchId);
    }

    private double getRate(String country) {
        double rate = 0;
        if (country.equals(XpConstants.COUNTRY_MY)) {
            rate = XpConstants.RATE_MY;
        }else if (country.equals(XpConstants.COUNTRY_VN)) {
            rate = XpConstants.RATE_VN;
        }else if(country.equals(XpConstants.COUNTRY_TH)) {
            rate = XpConstants.RATE_TH;
        }
        return rate;
    }

    private XpSellerResDto getItemInfo(String country, Long shopId, Integer limit, Integer offset) throws IOException {
        XpSellerResDto xpSellerResDto = null;
        if (country.equals(XpConstants.COUNTRY_MY)) {
            xpSellerResDto = getMyItemInfo(shopId, limit, offset);
        }else if (country.equals(XpConstants.COUNTRY_VN)) {
            xpSellerResDto = getVNItemInfo(shopId, limit, offset);
        }else if(country.equals(XpConstants.COUNTRY_TH)) {
            xpSellerResDto = getTHItemInfo(shopId, limit, offset);
        }
        return xpSellerResDto;
    }

    private XpSellerResDto getMyItemInfo(Long shopId, Integer limit, Integer offset) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://my.xiapibuy.com/api/v4/recommend/recommend?bundle=shop_page_category_tab_main&item_card=2&limit="+ limit +"&offset="+ offset +"&shopid="+ shopId +"&sort_type=1&tab_name=popular&upstream=search";
        log.info("URL = {}", url);
        HttpGet httpGet = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        XpSellerResDto responseData = new Gson().fromJson(responseStr, XpSellerResDto.class);

        return responseData;
    }

    private XpSellerResDto getVNItemInfo(Long shopId, Integer limit, Integer offset) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://shopee.vn/api/v4/recommend/recommend?bundle=shop_page_category_tab_main&item_card=2&limit="+ limit +"&offset="+ offset +"&shopid="+ shopId +"&sort_type=1&tab_name=popular&upstream=search";
        log.info("URL = {}", url);
        HttpGet httpGet = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        XpSellerResDto responseData = new Gson().fromJson(responseStr, XpSellerResDto.class);

        return responseData;
    }

    private XpSellerResDto getTHItemInfo(Long shopId, Integer limit, Integer offset) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://shopee.co.th/api/v4/recommend/recommend?bundle=shop_page_category_tab_main&item_card=2&limit="+ limit +"&offset="+ offset +"&shopid="+ shopId +"&sort_type=1&tab_name=popular&upstream=search";
        log.info("URL = {}", url);
        HttpGet httpGet = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        XpSellerResDto responseData = new Gson().fromJson(responseStr, XpSellerResDto.class);

        return responseData;
    }

    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {

        if (nowTime.getTime() == beginTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

}
